import time
import random
from PyQt5.QtCore import Qt
from PyQt5.Qt import QProgressBar, QFrame, QTimer, pyqtSignal, QShortcut
from PyQt5.QtWidgets import QGridLayout, QWidget, QLabel
from common.utils.NovishLogger import logger
from common.utils.design_pattern.observe_pattern import Observer
from .BaseWindow import BaseWindow

__doc__ = 'UI 进度条'

from ...system_status import SystemStatus


class UiProgress(QFrame, BaseWindow, Observer):
    sig = pyqtSignal(bool)

    def __init__(self):
        self.timer = QTimer()
        self.load_result = False
        self.step = 0
        self.resource_key = "load_result"
        super(UiProgress, self).__init__()

        self.setFixedSize(600, 200)

        self.setWindowTitle('Novish')
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground, True)

        self.SetWindowLocks()

    def showEvent(self, event):
        self.SetWindowCentered()
        self.timer.start(333)

    def _connect(self):
        self.timer.timeout.connect(self._update)
        self.progress.valueChanged.connect(lambda x: self.close() if x == 100 else None)

        QShortcut('F12', self).activated.connect(self._f12)

    def _update(self):
        """ 进度条更新 """
        self.step = self.step + random.choice(range(10))
        self.progress.setValue(self.step) if self.step <= 99 else None

        # TODO ready_p_cnt/ready_p_total 已弃用 为兼容旧版在此保留
        if self.load_result or (bool(set(['ready_p_cnt', 'ready_p_total']) & set(
                self.__dict__)) and self.ready_p_cnt.value == self.ready_p_total):
            self.timer.stop()
            self.progress.setValue(99)
            self.progress.setValue(100)
            self.sig.emit(True)

    def update_status(self, observable, extra_data=None):
        """
        根据数据更新界面
        @param observable:
        @param extra_data:
        @return:
        """
        if self.resource_key in extra_data:
            value = extra_data[self.resource_key]
            if value and isinstance(value, bool):
                self.load_result = value
            else:
                logger.error(f"Wrong type:{type(value)}, expected Bool")

    def _f12(self):
        self.value = 100
        self.sig.emit(True)

    def _initUI(self, mode=1):
        if mode == 1:
            self.grid_main = QGridLayout(self)

            self.progress = QProgressBar(self)
            self.progress.setFormat('  正在加载检测模块，请稍等LOADING... %p%')
            self.progress.setStyleSheet("""
                        QProgressBar{
                        border-radius:5px;
                        background-color: rgb(240,240,240);
                        text-align:center;
                        }
                        QProgressBar::chunk{
                        border-radius:10px;
                        background-color: rgb(0,175,219);
                        width:20px;
                        }
            """)

            self.grid_main.addWidget(self.progress, 0, 0)

        elif mode == 2:
            self.grid_main = QGridLayout(self)

            self.widget = QWidget(self)
            self.widget.setObjectName('widget')
            self.grid_inner = QGridLayout(self.widget)

            self.grid_main.addWidget(self.widget, 0, 0, 1, 1)

            self.label = QLabel(self.widget)
            self.label.setText('正在加载检测模块，请稍等LOADING...')
            self.label.setAlignment(Qt.AlignCenter)

            self.progress = QProgressBar(self.widget)
            self.progress.setObjectName('progress')

            self.grid_inner.addWidget(self.label, 0, 0)
            self.grid_inner.addWidget(self.progress, 1, 0)

            self.grid_main.setRowStretch(0, 1)
            self.grid_main.setRowStretch(1, 1)

            self.setStyleSheet(
                """
                    #widget {
                        background: #c0c0c0;
                        border-radius: 10px;
                        /*
                        opacity: 10;
                        border: 2px solid #c0c0c0;
                        */
                    }
                """
            )
